package bb.lanxing.activity.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import androidx.annotation.NonNull;

import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.common.config.Constants;
import bb.lanxing.common.config.UmengEventConst;
import bb.lanxing.manager.SPConstant;
import bb.lanxing.manager.ShareDialogMgr;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.ProPerms;
import bb.lanxing.mvp.presetner.ProModelImpl;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.service.DownloadService;
import bb.lanxing.util.BitmapHelper;
import bb.lanxing.util.CustomShareUtil;
import bb.lanxing.util.AppFileUtils;
import bb.lanxing.util.JsonUtil;
import bb.lanxing.util.text.TextUtils;
import bb.lanxing.view.BiciAlertDialogBuilder;
import bb.lanxing.view.ShareView;
import rx.Subscriber;
import rx.Subscription;
import rx.schedulers.Schedulers;

public class WebActivity extends WebBaseActivity {
    final private static String TAG = "WebActivity";

    public static final int SAVE_IMAGE_SIZE = 1080;

    public static String orderId;
    private boolean isNeedShare;
    private boolean isNeedShareAfterSave;
    ShareDialogMgr mShareDialogMgr;
    private WebViewBroadcastReceiver receiver;
    private String shareContent;
    private String shareImagePath;
    private String shareThumbUrl;
    private String shareTitle;
    private String shareUrl;
    private Subscription subscribe;
    private Map<String, String> imageMap = new HashMap();
    boolean mIsSharing = false;
    int shareType = 1;
    ShareView.ShareItemClickListener mShareItemClickListener = i -> {
        if (WebActivity.this.mIsSharing) {
            return;
        }
        WebActivity.this.mIsSharing = true;
        if (i == 9) {
            String str = WebActivity.this.shareUrl;
            Log.v(TAG, "ShareView, SHARE_TYPE_COPY_URL = " + WebActivity.this.shareUrl);
            if (TextUtils.isEmptyOrNull(str)) {
                str = WebActivity.this.webView.getUrl();
            }
            TextUtils.copyTextToClipBoard(WebActivity.this, str);
        } else {
            int i2 = WebActivity.this.shareType;
            if (i2 == 2) {
                CustomShareUtil.shareImage(WebActivity.this, BitmapHelper.captureWebViewLollipop(WebActivity.this.webView), i);
            } else if (i2 != 3) {
                String str2 = WebActivity.this.shareThumbUrl;
                Log.v(TAG, "ShareView, shareThumbUrl = " + WebActivity.this.shareThumbUrl);
                if (TextUtils.isEmptyOrNull(str2)) {
                    str2 = (String) WebActivity.this.imageMap.get(WebActivity.this.webView.getUrl());
                }
                String str3 = str2;
                Log.v(TAG,
                        "ShareView, thumbUrl = " + str3 + ", webView.getTitle() = " + WebActivity.this.webView.getTitle() + ", webView.getUrl() = " + WebActivity.this.webView.getUrl());
                WebActivity webActivity = WebActivity.this;
                CustomShareUtil.shareWebUrl(webActivity, webActivity.shareTitle, WebActivity.this.shareContent, str3,
                        (WebActivity.this.shareUrl == null || WebActivity.this.shareUrl.isEmpty()) ? WebActivity.this.webView.getUrl() :
                                WebActivity.this.shareUrl, i);
            } else if (android.text.TextUtils.isEmpty(WebActivity.this.shareImagePath)) {
                return;
            } else {
                File file = new File(WebActivity.this.shareImagePath);
                if (!file.exists()) {
                    return;
                }
                Bitmap readSampleBitmap = BitmapHelper.readSampleBitmap(Uri.fromFile(file), SAVE_IMAGE_SIZE);
                if (readSampleBitmap != null) {
                    readSampleBitmap = BitmapHelper.shrinkBitmap(readSampleBitmap, SAVE_IMAGE_SIZE, 0);
                }
                if (readSampleBitmap != null) {
                    CustomShareUtil.shareImage(WebActivity.this, readSampleBitmap, i);
                }
            }
        }
        if (WebActivity.this.webView.getUrl() != null) {
            MyHttpClient.webShareStatistics(new BiCiCallback() {
                @Override
                public void onResponseString(@NonNull String str4) throws JSONException {
                    Log.v(TAG, "payByAlipay, payInfo = " + str4);
                }
            }, WebActivity.this.webView.getUrl());
            if (WebActivity.this.webView.getUrl().contains(Constants.NEWS_URL)) {
                MobclickAgent.onEventValue(WebActivity.this, UmengEventConst.SHARE_NEWS, null, 1);
            } else if (WebActivity.this.webView.getUrl().contains(Constants.GAME_LIST_URL)) {
                MobclickAgent.onEventValue(WebActivity.this, UmengEventConst.SHARE_COMPETITION_LIST, null, 1);
            } else if (WebActivity.this.webView.getUrl().contains(Constants.GAME_DETAIL_URL)) {
                MobclickAgent.onEventValue(WebActivity.this, UmengEventConst.SHARE_COMPETITION_DETAIL, null, 1);
            }
        }
        WebActivity.this.shareType = 1;
        WebActivity.this.shareImagePath = null;
        WebActivity.this.mIsSharing = false;
        WebActivity.this.mShareDialogMgr.hide();
        WebActivity.this.afterShare(i);
    };

    public void afterShare(int i) {
    }

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        try {
            this.webView.setWebChromeClient(getWebChromeClient());
            this.webView.setWebViewClient(getWebViewClient());
            this.webView.addJavascriptInterface(new JsInteration(), "control");
            this.webView.loadUrl(this.webUrl);
            this.mShareDialogMgr = new ShareDialogMgr(this);
            ShareView shareView = new ShareView(this);
            shareView.buildType(new int[]{0, 1, 2, 3, 4, 9, 7});
            shareView.setShareItemClickListener(this.mShareItemClickListener);
            this.mShareDialogMgr.setContent(shareView);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected BaseWebChromeClient getWebChromeClient() {
        return new BaseWebChromeClient();
    }

    protected BaseWebViewClient getWebViewClient() {
        return new BaseWebViewClient() {
            @Override
            public void onPageFinished(WebView webView, String str) {
                super.onPageFinished(webView, str);
                WebActivity.this.uiHandler.postDelayed(() -> WebActivity.this.callJSFunction(), 500L);
            }

            @Override
            public void onLoadResource(WebView webView, String str) {
                super.onLoadResource(webView, str);
                Log.v(TAG, "onLoadResource, url = " + str);
                if ((str.contains(".png") || str.contains(".jpg") || str.contains(".jpeg")) && !WebActivity.this.imageMap.containsKey(webView.getUrl())) {
                    Log.v(TAG, "onLoadResource imageMap.put, view.getUrl() = " + webView.getUrl() + ", url = " + str);
                    WebActivity.this.imageMap.put(webView.getUrl(), str);
                }
            }
        };
    }

    private void registerReceiver() {
        if (this.receiver != null) {
            return;
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadService.ACTION_DOWNLOAD_COMPLETED);
        WebViewBroadcastReceiver webViewBroadcastReceiver = new WebViewBroadcastReceiver(this);
        this.receiver = webViewBroadcastReceiver;
        registerReceiver(webViewBroadcastReceiver, intentFilter, Context.RECEIVER_EXPORTED);
    }

    private void unregisterReceiver() {
        WebViewBroadcastReceiver webViewBroadcastReceiver = this.receiver;
        if (webViewBroadcastReceiver != null) {
            unregisterReceiver(webViewBroadcastReceiver);
            this.receiver = null;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        registerReceiver();
    }

    @Override
    public void onStop() {
        super.onStop();
        unregisterReceiver();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!SharedManager.getInstance().getBoolean(SPConstant.WECHAT_PAY_SUCCESS, false) || this.webView == null || this.webUrl == null) {
            return;
        }
        SharedManager.getInstance().setValue(SPConstant.WECHAT_PAY_SUCCESS, false);
        if (this.webUrl.contains(Constants.BUY_VIP_LINK)) {
            buyProInfo();
        }
        this.webView.loadUrl(this.webUrl);
    }

    @Override
    public void finish() {
        if (this.webUrl != null && this.webUrl.contains(Constants.BUY_VIP_LINK)) {
            buyProInfo();
        }
        super.finish();
    }

    public void buyProInfo() {
        if (App.getContext().getSigninUser() != null) {
            this.subscribe =
                    new ProModelImpl().getProInfo().observeOn(Schedulers.io()).subscribe(new Subscriber<>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable th) {
                        }

                        @Override
                        public void onNext(ProPerms proPerms) {
                        }
                    });
        }
    }

    @Override
    public void onDestroy() {
        Subscription subscription = this.subscribe;
        if (subscription != null) {
            subscription.unsubscribe();
        }
        super.onDestroy();
    }

    @Override
    public boolean onHomeBack() {
        if (this.homeBackable) {
            return super.onHomeBack();
        }
        return false;
    }

    @Override
    protected boolean onHitTestResult(WebView.HitTestResult hitTestResult) {
        if (hitTestResult.getType() == 5) {
            showImageOptions(hitTestResult.getExtra());
            return true;
        }
        return false;
    }

    private void showImageOptions(final String str) {
        new BiciAlertDialogBuilder(this).setItems(new CharSequence[]{getString(R.string.save), getString(R.string.share_image)},
                (dialogInterface, i) -> {
                    if (i == 0) {
                        WebActivity.this.saveImageToLocal(str, false);
                    } else if (i != 1) {
                    } else {
                        WebActivity.this.saveImageToLocal(str, true);
                    }
                }).show();
    }

    public void saveImageToLocal(String str, boolean z) {
        String buildExternalDirectoryPath = AppFileUtils.buildExternalDirectoryPath("download");
        if (android.text.TextUtils.isEmpty(buildExternalDirectoryPath)) {
            return;
        }
        Matcher matcher = Pattern.compile("^data:image/(.*);base64,(.*)").matcher(str);
        if (matcher.matches()) {
            String group = matcher.group(1);
            byte[] decode = Base64.decode(matcher.group(2), 0);
            File file = new File(buildExternalDirectoryPath, System.currentTimeMillis() + "." + group);
            AppFileUtils.writeFile(decode, file.getAbsolutePath());
            if (z) {
                onShareImage(file.getAbsolutePath());
                return;
            }
            return;
        }
        this.isNeedShareAfterSave = z;
        DownloadService.download(this, null, str, new File(buildExternalDirectoryPath, AppFileUtils.getName(str)).getAbsolutePath());
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem menuItem) {
        if (R.id.action_share == menuItem.getItemId()) {
            onShareClicked();
        }
        return super.onOptionsItemSelected(menuItem);
    }

    void onShareImage(String str) {
        if (android.text.TextUtils.isEmpty(str)) {
            return;
        }
        this.shareType = 3;
        this.shareImagePath = str;
        if (this.mShareDialogMgr.isShowing()) {
            return;
        }
        this.mShareDialogMgr.show(true);
    }

    public void onShareClicked() {
        getShareInfo();
        if (App.getContext().getSigninUser() == null) {
            App.getContext().userSignin();
        } else if (this.mShareDialogMgr.isShowing()) {
        } else {
            this.mShareDialogMgr.show(true);
        }
    }

    public String callJSFunction() {
        if (!isFinishing() && this.webView != null) {
            if (Build.VERSION.SDK_INT >= 19) {
                this.webView.evaluateJavascript("sendShare2Native()", str -> {
                    String replace = str.replace("\"", "");
                    Log.v(TAG, "evaluateJavascript, sendShare2Native, value=" + replace);
                    WebActivity.this.isNeedShare = "true".equals(replace);
                    WebActivity.this.toggleShareBtn(replace);
                });
            } else {
                this.webView.loadUrl("javascript:sendShare2Native(param)");
                toggleShareBtn((String) null);
            }
            getShareInfo();
        }
        return null;
    }

    private void getShareInfo() {
        this.webView.evaluateJavascript("sendPic2Native()", str -> {
            String replace = str.replace("\"", "");
            Log.v(TAG, "evaluateJavascript, sendPic2Native, value=" + replace);
            WebActivity.this.shareThumbUrl = replace;
        });
        this.webView.evaluateJavascript("sendTitle2Native()", str -> {
            String replace = str.replace("\"", "");
            Log.v(TAG, "evaluateJavascript, sendTitle2Native, value=" + replace);
            if (WebActivity.this.webView.getTitle().equals("蓝行商城")) {
                WebActivity webActivity = WebActivity.this;
                if (TextUtils.isEmptyOrNull(replace)) {
                    replace = "发现一家好店：蓝行商城";
                }
                webActivity.shareTitle = replace;
                return;
            }
            WebActivity webActivity2 = WebActivity.this;
            if (TextUtils.isEmptyOrNull(replace)) {
                replace = WebActivity.this.webView.getTitle();
            }
            webActivity2.shareTitle = replace;
        });
        this.webView.evaluateJavascript("sendContent2Native()", str -> {
            String replace = str.replace("\"", "");
            Log.v(TAG, "evaluateJavascript, sendContent2Native, value=" + replace);
            if (WebActivity.this.webView.getTitle().equals("蓝行商城")) {
                WebActivity webActivity = WebActivity.this;
                if (TextUtils.isEmptyOrNull(replace)) {
                    replace = "一家很棒的骑行装备店";
                }
                webActivity.shareContent = replace;
                return;
            }
            WebActivity webActivity2 = WebActivity.this;
            if (TextUtils.isEmptyOrNull(replace)) {
                replace = WebActivity.this.webView.getTitle();
            }
            webActivity2.shareContent = replace;
        });
    }

    public class JsInteration {
        public JsInteration() {
        }

        @JavascriptInterface
        public boolean pay(int i, String str) {
            WebActivity.orderId = str;
            if (i != 0) {
                if (i == 1) {
                    WebActivity.this.payByAlipay(str);
                }
            }
            //TODO:sun
            else {
                App.getContext().showMessage("您还未安装微信客户端，为您推荐扫码支付..");
                return false;
            }
            return true;
        }

        @JavascriptInterface
        public void share() {
            if (App.getContext().getSigninUser() == null) {
                App.getContext().userSignin();
                return;
            }
            WebActivity.this.shareType = 2;
            if (WebActivity.this.mShareDialogMgr.isShowing()) {
                return;
            }
            WebActivity.this.mShareDialogMgr.show(true);
        }
    }

    public void payByAlipay(String str) {
        MyHttpClient.payByAlipay(new BiCiCallback() {
            @Override
            public void onResponseString(@NonNull String str2) throws JSONException {
                String payInfo = WebActivity.this.getPayInfo(str2);
                Log.v(TAG, "payByAlipay, payInfo = " + payInfo);
                if (payInfo != null) {
                    //TODO:sun
                }
            }
        }, str);
    }

    public String getPayInfo(String str) {
        try {
            JSONObject jSONObject = new JSONObject(str);
            String stringValue = JsonUtil.getStringValue(/*ParameterPacketExtension.ELEMENT_NAME*/"parameter", jSONObject);
            String stringValue2 = JsonUtil.getStringValue("sign", jSONObject);
            String stringValue3 = JsonUtil.getStringValue("sign_type", jSONObject);
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    stringValue2 = URLEncoder.encode(stringValue2, StandardCharsets.UTF_8);
                } else {
                    stringValue2 = URLEncoder.encode(stringValue2, "UTF-8");
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return (stringValue + "&sign=\"" + stringValue2 + "\"") + "&sign_type=\"" + stringValue3 + "\"";
        } catch (JSONException e2) {
            e2.printStackTrace();
            return null;
        }
    }

    public static class WebViewBroadcastReceiver extends BroadcastReceiver {
        WeakReference<WebActivity> webActivityRef;

        WebViewBroadcastReceiver(WebActivity webActivity) {
            this.webActivityRef = new WeakReference<>(webActivity);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            WebActivity webActivity = this.webActivityRef.get();
            if (DownloadService.ACTION_DOWNLOAD_COMPLETED.equals(intent.getAction())) {
                String stringExtra = intent.getStringExtra(DownloadService.EXTRA_OUTPUT_PATH);
                if (webActivity == null || !webActivity.isNeedShareAfterSave) {
                    return;
                }
                webActivity.onShareImage(stringExtra);
            }
        }
    }

    @Override
    public void onActivityResult(int i, int i2, Intent intent) {
        super.onActivityResult(i, i2, intent);
        if (i == 1 && App.getContext().isUserSignin()) {
            this.webView.reload();
        }
    }

    public static void start(Context context, String title, String url) {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra("web_url", url);
        intent.putExtra("title", title);
        context.startActivity(intent);
    }
}